﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using Interfaces.CommonData;
using StockInfoLoader.Utils;

namespace StockInfoLoader
{
    public class SingleStockPriceLoader
    {
        private const int IDX_FIELD_DATE = 0;
        private const int IDX_FIELD_ADJ_PRICE = 6;

        // TODO: Common type to be used
        public List<StockPrice> LoadAdjustedStockPrices(string ticker, int tickerId, DateInterval dtInterval)
        {
            string pricesDump = LoadPricesAsString(ticker, tickerId, dtInterval);
            // convert comma separated string into list
            List<StockPrice> lstPrices = ConvertFromDump(pricesDump, tickerId);
            return lstPrices;
        }

        // TODO: Common type to be used
        public string LoadPricesAsString(string ticker, int tickerId, DateInterval dtInterval)
        {
            string pricesDump = string.Empty;
            string url = Utils.UrlHelper.GetPriceUrl(UrlHelper.Sources.YAHOO, ticker, dtInterval);
            ExtractorHelper.ExtractResults res =
                ExtractorHelper.ExtractHTTP(url, out pricesDump);

            // TODO: just skip this ticker if no data returned
            if (res == ExtractorHelper.ExtractResults.Error)
                return string.Empty;
            return pricesDump;

        }


        private List<StockPrice> ConvertFromDump(string dump, int tickerId)
        {
            List<StockPrice> lstPrices = new List<StockPrice>();

            using (StringReader sr = new StringReader(dump))
            {
                sr.ReadLine(); // skip field names
                while(true)
                {
                    string line = sr.ReadLine();
                    if (line == null)
                        break;

                    string[] values = line.Split(new char[] {','});
                    StockPrice p = new StockPrice();
                    p.Date = Convert.ToDateTime(values[IDX_FIELD_DATE]);
                    p.AdjPrice = Convert.ToDecimal(values[IDX_FIELD_ADJ_PRICE]);
                    p.StockId = tickerId;
                    lstPrices.Add(p);
                }
                
                
            }



            return lstPrices;
        }
    }
}
